
<template>
  <view class="container">
    <!-- 渐变标题栏 -->
    <view class="header-gradient">
      <view class="header-content">
        <uni-icons type="arrowleft" size="24" color="#fff" @click="navigateBack"></uni-icons>
        <text class="header-title">题库上传中心</text>
        <view style="width:24px"></view>
      </view>
      <view class="wave-divider"></view>
    </view>

    <!-- 主操作区 -->
    <view class="content-card">
      <!-- 文件上传区 -->
      <view class="upload-card" @click="chooseFile">
        <view class="upload-icon">
          <uni-icons type="cloud-upload" size="48" color="#4a90e2"></uni-icons>
        </view>
        <text class="upload-tip">{{ fileName || '点击选择Excel文件' }}</text>
        <text class="upload-subtip">支持.xlsx/.xls格式，大小不超过20MB</text>
      </view>

      <!-- 操作按钮组 -->
      <view class="action-group">
        <button 
          class="action-button download"
          @click="downloadTemplate"
          :disabled="downloading"
          :style="{opacity: downloading ? 0.7 : 1}"
        >
          <uni-icons type="download" size="20" color="#fff"></uni-icons>
          {{ downloading ? `下载中 ${downloadProgress}%` : '下载模板' }}
        </button>

        <button 
          class="action-button submit"
          @click="uploadFile"
          :disabled="!filePath || uploading"
          :style="{opacity: (!filePath || uploading) ? 0.7 : 1}"
        >
          <uni-icons type="upload" size="20" color="#fff"></uni-icons>
          {{ uploading ? '上传中...' : '立即上传' }}
        </button>
      </view>

      <!-- 状态提示 -->
      <view v-if="savedFilePath" class="status-card">
        <uni-icons type="info" size="18" color="#4a90e2"></uni-icons>
        <text class="status-text">模板已保存至：{{ savedFilePath }}</text>
      </view>
    </view>

    <!-- 进度条 -->
    <view v-if="downloading" class="progress-bar">
      <view class="progress-inner" :style="{width: downloadProgress + '%'}"></view>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      user: {},
      filePath: '',
      fileName: '',
      uploading: false,
      downloading: false,
      downloadProgress: 0,
      savedFilePath: '',
      cloudTemplateUrl: 'https://mp-af23f9bf-4158-4e1e-a256-55391c393d0c.cdn.bspapp.com/cloudstorage/template.xlsx'
    };
  },
  onLoad() {
    this.loadUserData();
  },
  methods: {
    loadUserData() {
      const user = uni.getStorageSync('user') || {};
      if (!user.id) {
        uni.redirectTo({ url: '/pages/student/login' });
        return;
      }
    },
    chooseFile() {
      const platform = uni.getSystemInfoSync().platform;
      if (platform === 'ios' || platform === 'android') {
        uni.chooseFile({
          count: 1,
          extension: ['.xlsx', '.xls'],
          success: (res) => {
            this.filePath = res.tempFilePaths[0];
            this.fileName = res.tempFiles[0].name;
            uni.showToast({ title: '文件选择成功', icon: 'success' });
          },
          fail: (err) => {
            console.error('选择文件失败:', err);
            uni.showToast({ title: '选择文件失败', icon: 'none' });
          }
        });
      } else if (platform === 'web') {
        uni.chooseFile({
          count: 1,
          extension: ['.xlsx', '.xls'],
          success: (res) => {
            this.filePath = res.tempFilePaths[0];
            this.fileName = res.tempFiles[0].name;
            uni.showToast({ title: '文件选择成功', icon: 'success' });
          },
          fail: (err) => {
            console.error('选择文件失败:', err);
            uni.showToast({ title: '选择文件失败', icon: 'none' });
          }
        });
      } else {
        wx.chooseMessageFile({
          count: 1,
          type: 'file',
          extension: ['xlsx', 'xls'],
          success: (res) => {
            this.filePath = res.tempFiles[0].path;
            this.fileName = res.tempFiles[0].name;
            uni.showToast({ title: '文件选择成功', icon: 'success' });
          },
          fail: (err) => {
            console.error('选择文件失败:', err);
            uni.showToast({ title: '选择文件失败', icon: 'none' });
          }
        });
      }
    },
    async uploadFile() {
      if (!this.filePath) {
        uni.showToast({ title: '请选择文件', icon: 'none' });
        return;
      }
      this.uploading = true;
      try {
        // 上传文件到云存储
        const uploadRes = await uniCloud.uploadFile({
          filePath: this.filePath,
          cloudPath: `questions_${Date.now()}.xlsx`
        });
        if (!uploadRes.fileID) {
          throw new Error('文件上传失败，未返回 fileID');
        }

        // 调用云函数处理 Excel 文件
        const res = await uniCloud.callFunction({
          name: 'uploadQuestionsExcel',
          data: { file_id: uploadRes.fileID }
        });

        if (res.result.code === 0) {
          uni.showToast({ 
            title: `成功上传${res.result.data.count}道题目`, 
            icon: 'success' 
          });
          this.filePath = '';
          this.fileName = '';
        } else {
          uni.showToast({ 
            title: res.result.msg || '上传失败', 
            icon: 'none',
            duration: 3000
          });
        }
      } catch (e) {
        console.error('上传失败:', e);
        uni.showToast({ 
          title: `上传失败: ${e.message || '未知错误'}`, 
          icon: 'none',
          duration: 3000
        });
      } finally {
        this.uploading = false;
      }
    },
    downloadTemplate() {
      this.downloading = true;
      this.downloadProgress = 0;
      this.savedFilePath = '';
      uni.downloadFile({
        url: this.cloudTemplateUrl,
        success: (res) => {
          if (res.statusCode === 200) {
            const fileSystemManager = wx.getFileSystemManager();
            const savePath = `${wx.env.USER_DATA_PATH}/template_${Date.now()}.xlsx`;
            fileSystemManager.saveFile({
              tempFilePath: res.tempFilePath,
              filePath: savePath,
              success: (saveRes) => {
                const savedPath = saveRes.savedFilePath || savePath;
                this.savedFilePath = savedPath;
                uni.showToast({ 
                  title: '模板下载成功', 
                  icon: 'success' 
                });
                uni.showModal({
                  title: '文件下载完成',
                  content: '是否立即打开模板文件？',
                  confirmText: '打开',
                  cancelText: '取消',
                  success: (modalRes) => {
                    if (modalRes.confirm) {
                      uni.openDocument({
                        filePath: savedPath,
                        fileType: 'xlsx',
                        success: () => {
                          console.log('文件打开成功');
                        },
                        fail: (err) => {
                          console.error('打开文件失败:', err);
                          uni.showToast({ 
                            title: '无法直接打开文件，请通过其他应用查看', 
                            icon: 'none',
                            duration: 3000
                          });
                        }
                      });
                    }
                  }
                });
              },
              fail: (err) => {
                console.error('保存模板失败:', err);
                uni.showToast({ 
                  title: `保存模板失败: ${err.errMsg || '未知错误'}`, 
                  icon: 'none' 
                });
              }
            });
          } else {
            uni.showToast({ 
              title: `下载模板失败: 状态码 ${res.statusCode}`, 
              icon: 'none' 
            });
          }
        },
        fail: (err) => {
          console.error('下载模板失败:', err);
          uni.showToast({ 
            title: `下载模板失败: ${err.errMsg || '未知错误'}`, 
            icon: 'none' 
          });
        },
        complete: () => {
          this.downloading = false;
          this.downloadProgress = 0;
        },
        onProgressUpdate: (res) => {
          this.downloadProgress = res.progress;
        }
      });
    }
  }
};
</script>

<style scoped>
/* 容器样式 */
.container {
  background: #f8f9fa;
  min-height: 100vh;
}

/* 渐变标题栏 */
.header-gradient {
  padding: 24px 20px 60px;
  background: linear-gradient(135deg, #4a90e2, #5aa1ff);
  position: relative;
}

.header-content {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 16px;
}

.header-title {
  color: #fff;
  font-size: 18px;
  font-weight: 600;
}

.wave-divider {
  height: 20px;
  background: url('data:image/svg+xml;utf8,<svg viewBox="0 0 1200 40" xmlns="http://www.w3.org/2000/svg"><path d="M0 40L1200 0V40H0z" fill="%23f8f9fa"/></svg>');
  position: absolute;
  bottom: -1px;
  left: 0;
  right: 0;
}

/* 内容卡片 */
.content-card {
  background: #fff;
  border-radius: 16px;
  margin: -40px 20px 20px;
  padding: 24px;
  box-shadow: 0 8px 24px rgba(74,144,226,0.1);
}

/* 上传区域 */
.upload-card {
  border: 2px dashed rgba(74,144,226,0.3);
  border-radius: 12px;
  padding: 32px 16px;
  display: flex;
  flex-direction: column;
  align-items: center;
  transition: all 0.3s;
  background: rgba(74,144,226,0.03);
}

.upload-card:active {
  transform: scale(0.98);
  background: rgba(74,144,226,0.05);
}

.upload-icon {
  margin-bottom: 12px;
}

.upload-tip {
  font-size: 16px;
  color: #333;
  margin-bottom: 8px;
}

.upload-subtip {
  font-size: 12px;
  color: #999;
}

/* 操作按钮 */
.action-group {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 16px;
  margin: 24px 0;
}

.action-button {
  height: 48px;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  font-size: 14px;
  transition: all 0.2s;
}

.action-button:active {
  transform: scale(0.96);
}

.download {
  background: #34c759;
}

.submit {
  background: #4a90e2;
}

/* 状态提示 */
.status-card {
  background: rgba(74,144,226,0.05);
  border-radius: 8px;
  padding: 12px;
  display: flex;
  align-items: center;
  gap: 8px;
}

.status-text {
  font-size: 12px;
  color: #666;
  flex: 1;
}

/* 进度条 */
.progress-bar {
  height: 4px;
  background: rgba(74,144,226,0.1);
  margin: 0 20px;
  border-radius: 2px;
}

.progress-inner {
  height: 100%;
  background: #4a90e2;
  border-radius: 2px;
  transition: width 0.3s ease;
}
</style>